from rest_framework import serializers
from .models import OauthQQUser
from users.models import User
from .utils import OAuthQQ
from django_redis import get_redis_connection


#QQ登录创建用户的序列化器， 因为有两个模型类，所以不能继承自Modelserializer
class QQAuthUserSerializer(serializers.Serializer):
    #是外界request。data请求体传入的数据
    access_token = serializers.CharField(label='操作凭证')
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3456789]\d{9}$')
    sms_code = serializers.CharField(label='短信验证码')
    password = serializers.CharField(label='密码', min_length=8, max_length=20)

    #验证
    def validate(self, data):

        """校验access_token"""
        access_token = data['access_token']
        #将签名的access_token还原获取openid
        openid = OAuthQQ.check_save_user_token(access_token)

        if not openid:
            raise serializers.ValidationError('access_token已经失效')

        #将openid放到字典中，供后面使用
        data['openid'] = openid

        #校验短信验证码
        mobile = data['mobile']
        sms_code = data['sms_code']
        #从数据库中读取出短信验证码
        redis_conn = get_redis_connection('verify_codes')
        real_sms_code = redis_conn.get('sms_%s' % mobile)
        #对比
        if sms_code != real_sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')

        #如果用户存在， 则检验密码
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            pass
        else:
            password = data['password']
            if not user.check_password(password):
                raise serializers.ValidationError('密码不正确')
            #将user保存到字典中，供后面使用
            data['user'] = user

        return data

    #绑定openid到用户上
    def create(self, validated_data):

        user = validated_data.get('user')

        #判断用户是否存在，存在就直接绑定openid， 不存在就创建新用户再绑定openid
        if not user:
            user = User.objects.create_user(
                username=validated_data['username'],
                mobile= validated_data['mobile'],
                password=validated_data['password']
            )

        #将用户绑定openid
        OauthQQUser.objects.create(
                user=user,
                openid=validated_data['openid']
        )
        #返回用户数据
        return user
